#include<stdio.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<netinet/in.h>//结构体，方便赋值
#include<stdlib.h>

int main(int argc,char *argv[])
{
    if(argc!=3)
    {
        printf("invalid number!\n");
        return -1;
    }

    int sock =socket(AF_INET,SOCK_STREAM,0);
    if(sock<0)
    {
        perror("socket:");
        return -1;
    }

    int on=1;
    if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(int))<0)//setsockopt 函数设置套接字选项
    {//SO_REUSEADDR 即重用地址选项,SOL_SOCKET 即套接字级别
        perror("setsockopt:");
        return -1;
    }

    struct sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_port=htons(atoi(argv[2]));
    addr.sin_addr.s_addr=inet_addr(argv[1]);
    if(bind(sock,(struct sockaddr*)&addr,sizeof(addr))!=0)
    {
        perror("bind:");
    }
    if(listen(sock,10)!=0)
    {
        perror("listen:");
        return -1;
    }

    struct sockaddr_in Clientaddr;
    socklen_t len=sizeof(Clientaddr);
    int acceptSock=0;
    if((acceptSock= accept(sock,(struct sockaddr *)&Clientaddr,&len))<0)
    {
        perror("accept:");
        return -1;
    }
    while(1)
    {
        char temp[100]={0};
        if(recv(acceptSock,temp,100,0)<0)
        {
            perror("recv: ");
        }
        printf("recv : %s\n",temp);
    }
    return  0;
}